package com.jsh.erp;

import com.alibaba.fastjson.JSON;
import com.jsh.erp.service.redis.RedisService;
import com.jsh.erp.utils.BaseResponseInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Resource
    private RedisService redisService;
    @Autowired
    private AuthProperties authProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        String toPath = request.getHeaders().getFirst("X-To-Path");
        String token = request.getHeaders().getFirst("X-Access-Token");
        if(authProperties.getWhiteList().contains(path)) {
            return chain.filter(exchange);
        }
        String funcListString = redisService.getObjectFromHash(token, "funcList");
        if(log.isDebugEnabled()){
            log.debug("funcListString:{}",funcListString);
            log.debug("toPath:{}",toPath);
        }
        if(StringUtils.hasText(funcListString)) {
            List<String> funcList = Arrays.stream(funcListString.split(",")).collect(Collectors.toList());
            funcList.add("/dashboard/analysis");//首页都可以访问
            if(!funcList.contains(toPath)) {
                log.error("无权访问：{}, {}", toPath, path);
                return unAuth(exchange);
            }
        } else {
            log.warn("路径错误：{}, {}", toPath, path);
        }

        return chain.filter(exchange);
    }

    public Mono<Void> unAuth(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.FORBIDDEN);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
        BaseResponseInfo info = new BaseResponseInfo();
        info.code = 403;
        info.data = "无权访问";
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(info).getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return 2;
    }
}
